

<template>
    <div class="sdy-search">
        <SdyHeader title="啥都没">
        <!-- title必填 具名插槽可以代替 -->
        <!-- 这里的#是与具名插槽相对应 -->
            <template #left>
                <van-icon class="back-btn" name="arrow-left" />
            </template>
            <template #title>
                <van-search v-model="searchText" shape="round" background="red" placeholder="请输入搜索关键词" />
            </template>
            <template #right>
                <van-button @click="searchhandler" type="success" size="small">搜索</van-button>
            </template>
        </SdyHeader>

        <!-- 没有文本的时候显示-->
        <!-- <SdySearchHistory v-if="!searchText"></SdySearchHistory> -->
         <!-- 有文本的时候显示-->
        <!-- <SdySearchList v-else></SdySearchList> -->

        <!-- 方式2 添加一个动态组件component -->
        <!-- 如果searchText 为true就渲染SdySearchList -->
        <!-- 如果searchText 为false就渲染SdySearchHistory-->
        <component :is="searchText ? SdySearchList : SdySearchHistory"></component>
        
    

    </div>
</template>

<script setup lang="ts">
import SdySearchHistory from './component/SdySearchHistory.vue';
import SdySearchList from './component/SdySearchList.vue';
import {ref,watch,provide} from 'vue'
import { useRouter,type Router } from 'vue-router';
import {searchListApi} from '@/api/goods'
import type {MyHotItem} from '@/config/inter'

const $router:Router = useRouter()

// 根据v-if判断需要显示搜索历史还是文本
const searchText = ref<string>('')

const searchhandler = ()=>{
    // ref应用在逻辑中要加value
    // console.log(searchText.value)
    const text = searchText.value.trim()
    if(!text) return 
    $router.push({path:'/goodslist',query:{search:text}})
}

// 随着搜索关键字的变化实时展示最新数据

// 准备一个数据 接收搜索列表
const searchList = ref<MyHotItem[]>([])

watch(searchText,async()=>{
    if(!searchText.value.trim()) return
    const res = await searchListApi(searchText.value.trim())
    // console.log(res)
    searchList.value = res.data
})


provide('searchList',searchList)

</script>

<style scoped lang="scss">
.back-btn{
   font-size: 24px;
}
</style>